package com.mcp_life.module.mcpclientmodules.repository;

import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.vectorstore.SimpleVectorStore;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.time.LocalDateTime;
import java.util.Objects;
import java.util.Properties;
@RequiredArgsConstructor
@Slf4j
@Component
public class LocalFileRepository implements FileRepository{
    private final VectorStore vectorStore;
    //会话id与文件的映射关系，方便查询会话历史时重新加载文件。
    private final Properties chatFiles=new Properties();
    @Override
    public boolean save(String chatId, Resource resource) {
        log.info("调用save");
        //2保存到本地磁盘
        String filename=resource.getFilename();
        File target=new File(Objects.requireNonNull(filename));
        if (!target.exists()){
            try {
                Files.copy(resource.getInputStream(),target.toPath());
            } catch (Exception e) {
                log.error("保存文件失败",e);
                return false;
            }
        }
        log.info("开始保存文件");
        //保存映射关系
        chatFiles.put(chatId,filename);
        return true;
    }

    @Override
    public Resource getFile(String chatId) {
        //获取文件
        return new FileSystemResource(chatFiles.getProperty(chatId));
    }
    /**
     * 持久化
     */
    @PostConstruct
    public void init(){
        //初始化
       FileSystemResource pdfResource=new FileSystemResource("chat-pdf.properties");
       if (pdfResource.exists()){
           try {
               chatFiles.load(new BufferedInputStream(pdfResource.getInputStream()));
           } catch (Exception e) {
               log.error("加载文件失败",e);
           }
       }
       //尝试从磁盘读取向量库
       FileSystemResource vectorResource=new FileSystemResource("chat-pdf.json");
       if (vectorResource.exists()){
           try {
               SimpleVectorStore simpleVectorStore=(SimpleVectorStore) vectorStore;
               simpleVectorStore.load(vectorResource);
           } catch (Exception e) {
               log.error("加载向量库失败",e);
           }
       }
    }

    /**
     * 在项目停机时持久化
     */
    @PreDestroy
    private void persistent(){
        //持久化
        try {
            chatFiles.store(new FileWriter("chat-pdf.properties"), String.valueOf(LocalDateTime.now()));
            SimpleVectorStore simpleVectorStore=(SimpleVectorStore) vectorStore;
            simpleVectorStore.save(new File("chat-pdf.json"));
        } catch (IOException e){
            throw new RuntimeException(e);
        }
    }
}
